package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.constant.CacheConstants;
import com.qk.domain.business.BusinessCountDo;
import com.qk.domain.clue.ClueCountDo;
import com.qk.management.aop.anno.Cacheable;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.ReportOverviewService;
import com.qk.vo.portal.PortalVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings("all")
public class ReportOverviewServiceImpl implements ReportOverviewService {
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private StringRedisTemplate redisClient;

    private static final String CACHE_PORTAL_KEY_PREFIX = "qk:portal:";
    @Override
    public PortalVo reportOverviewWitchCache() {
        // 直接调用reportOverview()方法，统一使用带@Cacheable注解的实现
        return reportOverview();
    }
    @Cacheable(
            keyPrefix = CacheConstants.CACHE_PORTAL_KEY_PREFIX,
            expireTime = 1L,
            expireTimeUnit = TimeUnit.MINUTES
    )
    @Override
    public PortalVo reportOverview() {
        ClueCountDo clueCountDo =clueMapper.selectCountClue();
        BusinessCountDo businessCountDo =businessMapper.selectCountBusiness();
        PortalVo vo = BeanUtil.copyProperties(clueCountDo, PortalVo.class);
        BeanUtil.copyProperties(businessCountDo, vo);
        return vo;
    }
    
    /**
     * 清理旧缓存，立即删除Redis中所有相关的缓存数据
     */
    public void clearOldCache() {
        try {
            // 根据CacheableAspect的实现，缓存键是keyPrefix+方法名
            String cacheKey = CacheConstants.CACHE_PORTAL_KEY_PREFIX + "reportOverview";
            redisClient.delete(cacheKey);
            log.info("成功清理旧缓存: {}", cacheKey);
            
            // 同时清理可能存在的旧格式缓存键
            String oldCacheKey = CACHE_PORTAL_KEY_PREFIX + "reportOverview";
            if (redisClient.hasKey(oldCacheKey)) {
                redisClient.delete(oldCacheKey);
                log.info("成功清理旧格式缓存: {}", oldCacheKey);
            }
        } catch (Exception e) {
            log.error("清理缓存失败", e);
        }
    }
}
